import 'package:decimal/decimal.dart';
import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/config/res_zero_tube_entity.dart';
import 'package:flutter_deer/database/beans/list_advance_pre_pay_order_entity.dart';
import 'package:flutter_deer/res/resources.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/util/input_formatter/mny_format.dart';
import 'package:flutter_deer/util/input_formatter/money_util.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:get/get.dart';


class MatchPrePayListDialog extends StatefulWidget { // 添加默认选中的油单ID列表参数

  const MatchPrePayListDialog({super.key, this.defaultSelectedEnergyOrderIds});

  final String? defaultSelectedEnergyOrderIds;

  @override
  State<MatchPrePayListDialog> createState() => _MatchPrePayListDialogState();
}

class _MatchPrePayListDialogState extends State<MatchPrePayListDialog> {
  final RxList<ListAdvancePrePayOrderList> _orderList = <ListAdvancePrePayOrderList>[].obs;
  final RxList<ListAdvancePrePayOrderList> _energyOrderList = <ListAdvancePrePayOrderList>[].obs;
  late AppZeroModConfig? config;
  final mProvider = Get.find<CashierPageProvider>();
  final RxList<String> _selectedOrderIds = <String>[].obs;
  final RxList<String> _selectedEnergyOrderIds = <String>[].obs;
  final RxString _canMatchDes = ''.obs;

  @override
  void initState() {
    super.initState();
    config = AppZeroModConfig.getConfig();
    Future.microtask(() {
      if (widget.defaultSelectedEnergyOrderIds != null) {
        _selectedEnergyOrderIds.add(widget.defaultSelectedEnergyOrderIds!);
      }
    });
    _requestOrderList();
    // 监听选中订单变化
    _selectedOrderIds.listen((event) {
      _canMatch();
    });
    // 监听选中油单变化
    _selectedEnergyOrderIds.listen((event) {
      _canMatch();
    });
  }

  /// 根据选择的单子和油单，判断是否可以匹配
  bool _canMatch() {
    if (_selectedOrderIds.isEmpty || _selectedEnergyOrderIds.isEmpty) {
      // 有选中的订单和油单
      _canMatchDes.value = '请选择订单和油单';
      return false;
    }
    // 计算选择的订单金额
    String totalAmount = '0';
    for (final String orderId in _selectedOrderIds) {
      final ListAdvancePrePayOrderList? order = _orderList.firstWhereOrNull((element) => element.orderId == orderId);
      if (order != null) {
        totalAmount = totalAmount.plus(order.orderAmount!);
      }
    }
    // 计算选择的油单金额
    String totalEnergyAmount = '0';
    for (final String energyOrderId in _selectedEnergyOrderIds) {
      final ListAdvancePrePayOrderList? order = _energyOrderList.firstWhereOrNull((element) => element.energyOrderId == energyOrderId);
      if (order != null) {
        totalEnergyAmount = totalEnergyAmount.plus(order.goodsTotalPrice!.toYuan!);
      }
    }
    // 比较金额 两者之差小于等于0.01
    final double difference = (Decimal.parse(totalAmount) - Decimal.parse(totalEnergyAmount)).abs().toDouble();
    // 比较金额 两者之差小于等于配置的误差金额
    final double mismatchAmount = config?.orderMismatchAmount ?? 0.0;
    if (difference <= mismatchAmount) {
      _canMatchDes.value = '可以匹配!';
      return true;
    }
    _canMatchDes.value = '不能匹配，金额差为￥${difference.toString()}';
    return false;
  }

  /// 请求可合并的油单列表
  void _requestOrderList() {
    mProvider.requestAdvanceOrderStatisticsPage(
      pageSize: 100,
      onSuccessCallBack: (data) {
        if (data?.list != null) {
          _orderList.assignAll(data!.list!);
        }
      },
    );
    mProvider.requestUnPayOrderList(
      onSuccessCallBack: (data) {
        if (data?.list != null) {
          _energyOrderList.assignAll(data!.list!);
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
      child: SizedBox(
        width: screenSize.width * 0.8,
        height: screenSize.height * 0.8,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Gaps.vGap15,
            _buildHeader(),
            Expanded(
              child: Row(
                children: [
                  Expanded(
                    child: Column(
                      children: [const Text('预支付订单（多选）', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), Gaps.vGap8, Expanded(child: _buildOrderList())],
                    ),
                  ),
                  const VerticalDivider(width: 1, thickness: 1, color: Colors.grey),
                  Expanded(
                    child: Column(
                      children: [const Text('未支付油单（单选）', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), Gaps.vGap8, Expanded(child: _buildUnPayOrderList())],
                    ),
                  ),
                ],
              ),
            ),
            Gaps.vGap15,
            Center(
                child: PressBlueButton(
                    width: 150,
                    height: 40,
                    text: '确 认 匹 配',
                    onPressed: () => {
                          if (_canMatch())
                            {
                              mProvider.requestMtMatch(
                                  orderIds: _selectedOrderIds,
                                  energyOrderIds: _selectedEnergyOrderIds,
                                  onSuccessCallBack: () {
                                    Toast.show('匹配成功');
                                    Navigator.of(context).pop();
                                  })
                            }
                          else
                            {Toast.show(_canMatchDes.value)}
                        })),
            Gaps.vGap15,
          ],
        ),
      ),
    );
  }

  /// 构建标题栏
  Widget _buildHeader() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        Row(crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.alphabetic, children: <Widget>[
          const SizedBox(width: 20),
          Text('订单匹配', style: TextStyles.textBold24.copyWith(color: Colours.dark_bg_color)),
          const SizedBox(width: 10),
          Obx(
            () => RichText(
              text: TextSpan(
                children: [
                  TextSpan(text: '请选择油单和预支付单，当前误差配置 ', style: TextStyles.textSize16.copyWith(color: Colours.orange)),
                  TextSpan(text: '[${config?.orderMismatchAmount}元]', style: TextStyles.textSize16.copyWith(color: Colours.green)),
                  TextSpan(text: '\t\t\t${_canMatchDes.value}', style: TextStyles.textSize16.copyWith(color: Colours.red)),
                ],
              ),
            ),
          )
        ]),
        IconButton(
          icon: const Icon(Icons.close),
          onPressed: () {
            Navigator.of(context).pop();
          },
        ),
      ],
    );
  }

  /// 构建订单列表
  Widget _buildOrderList() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Obx(
        () => ListView.builder(
          itemCount: _orderList.length,
          itemBuilder: (context, index) {
            if (index == _orderList.length) {
              return const Padding(
                padding: EdgeInsets.all(8.0),
                child: Center(child: CircularProgressIndicator()),
              );
            }
            final order = _orderList[index];
            return _buildOrderItem(order, index);
          },
        ),
      ),
    );
  }

  Widget _buildUnPayOrderList() {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 20),
      child: Obx(
        () => ListView.builder(
          itemCount: _energyOrderList.length,
          itemBuilder: (context, index) {
            if (index == _energyOrderList.length) {
              return const Padding(
                padding: EdgeInsets.all(8.0),
                child: Center(child: CircularProgressIndicator()),
              );
            }
            final order = _energyOrderList[index];
            return _buildUnPayOrderItem(order, index);
          },
        ),
      ),
    );
  }

  /// 构建订单项
  Widget _buildOrderItem(ListAdvancePrePayOrderList order, int index) {
    final isEven = index % 2 == 0;
    return ColoredBox(
      color: isEven ? const Color(0xFFE3F2FD) : const Color(0xFFF5F7FA), // 浅蓝色
      // color: isEven ? Theme.of(context).colorScheme.secondaryContainer : Theme.of(context).colorScheme.surface,
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        title: Row(
          children: <Widget>[
            Expanded(flex: 2, child: Text('${order.payTime}', textAlign: TextAlign.center)),
            Expanded(flex: 2, child: Text('${order.payTypeNames}', textAlign: TextAlign.center)),
            Expanded(flex: 2, child: Text('${order.phone?.phone}', textAlign: TextAlign.center)),
            Expanded(flex: 2, child: Text('${order.shelfNoList}号枪\t\t ${order.goodsNameList}', textAlign: TextAlign.center)),
            Expanded(flex: 1, child: Text('￥${order.orderAmount}', style: const TextStyle(color: Color(0xFFD76B02)), textAlign: TextAlign.center)),
            // 添加check
            Expanded(
                flex: 1,
                child: Obx(
                  () => Checkbox(
                      value: _selectedOrderIds.contains(order.orderId),
                      onChanged: (value) {
                        if (value != null && value) {
                          // 选中
                          _selectedOrderIds.add(order.orderId!);
                        } else {
                          // 取消选中
                          _selectedOrderIds.remove(order.orderId);
                        }
                      }),
                ))
          ],
        ),
        onTap: () {
          // 点击整行也可以切换选中状态
          if (_selectedOrderIds.contains(order.orderId)) {
            _selectedOrderIds.remove(order.orderId);
          } else {
            _selectedOrderIds.add(order.orderId!);
          }
        },
      ),
    );
  }

  /// 构建订单项
  Widget _buildUnPayOrderItem(ListAdvancePrePayOrderList order, int index) {
    final isEven = index % 2 != 0;
    return ColoredBox(
      color: isEven ? const Color(0xFFE3F2FD) : const Color(0xFFF5F7FA), // 浅蓝色
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
        title: Row(
          children: <Widget>[
            Expanded(
                flex: 1,
                child: Obx(
                  () => Checkbox(
                      value: _selectedEnergyOrderIds.contains(order.energyOrderId),
                      onChanged: (value) {
                        if (value != null && value) {
                          // 选中
                          _selectedEnergyOrderIds.assign(order.energyOrderId!);
                        } else {
                          // 取消选中
                          _selectedEnergyOrderIds.remove(order.energyOrderId);
                        }
                      }),
                )),
            Expanded(flex: 2, child: Text('￥${order.goodsTotalPrice?.toYuan}', style: const TextStyle(color: Color(0xFFD76B02)), textAlign: TextAlign.center)),
            Expanded(flex: 4, child: Text('${order.shelfNo}号枪 | ${order.mchGoodsName} | ${order.goodsQuantity?.toYuan}${order.goodsUnit}', textAlign: TextAlign.center)),
            Expanded(flex: 4, child: Text('${order.createTime}', textAlign: TextAlign.center)),
          ],
        ),
        onTap: () {
          // 点击整行也可以切换选中状态
          if (_selectedEnergyOrderIds.contains(order.energyOrderId)) {
            _selectedEnergyOrderIds.remove(order.energyOrderId);
          } else {
            _selectedEnergyOrderIds.assign(order.energyOrderId!);
          }
        },
      ),
    );
  }
}
